package cn.itcast.usermanage.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.itcast.usermanage.bean.DateGridResult;
import cn.itcast.usermanage.pojo.User;
import cn.itcast.usermanage.service.UserService;

@Controller
@RequestMapping("user")
public class UserController {
	/**
	 * 逻辑:
	 * 1.确认同步还是异步
	 * 2.携带那些参数?参数是否必须?
	 * 3.返回那些结果
	 */
	//注入service
	@Autowired
	private UserService userService;
	
	@RequestMapping("page/{topage}")
	public String toPage(@PathVariable("topage")String topage) {
		return topage;
	}
	
	//分页查询客户列表
	@ResponseBody
	@RequestMapping(value="list",method=RequestMethod.POST)
	public DateGridResult queryPageUserList(
			@RequestParam(value="page",defaultValue="1")Integer pageNum,
			@RequestParam(value="rows",defaultValue="5")Integer pageSize){
		//调用service层方法查询
			
		return userService.queryPageUserList(pageNum,pageSize);
	}
	
	//添加用户
	@ResponseBody
	@RequestMapping(value="save",method=RequestMethod.POST)
	public Map<String,Integer> save(User user){
		Map<String,Integer> requestMap=new HashMap<>();
		try {
			userService.save(user);
			requestMap.put("status", 200);
		} catch (Exception e) {			
			e.printStackTrace();
		}	
		return requestMap;
	}
	//删除用户
	@ResponseBody
	@RequestMapping(value="delete",method=RequestMethod.POST)
	public Map<String,Integer> delete(String ids){
		Map<String,Integer> requestMap=new HashMap<>();
		try {
			userService.delete(ids);
			requestMap.put("status", 200);
		} catch (Exception e) {			
			e.printStackTrace();
		}	
		return requestMap;
	}
	//删除用户
	@ResponseBody
	@RequestMapping(value="delete1",method=RequestMethod.POST)
	public Map<String,Integer> delete1(Long[] ids){
		Map<String,Integer> requestMap=new HashMap<>();
		try {
			userService.delete1(ids);
			requestMap.put("status", 200);
		} catch (Exception e) {			
			e.printStackTrace();
		}	
		return requestMap;
	}
	
	//excel的到出功能
	@RequestMapping(value="export/excel",method=RequestMethod.POST)
	public ModelAndView exportExcel(
			@RequestParam(value="page",defaultValue="1")Integer pageNum,
			@RequestParam(value="rows",defaultValue="5")Integer pageSize) {
		//创建视图模型并指定视图名称
		ModelAndView mv = new ModelAndView("excelView");
		//查询分页数据
		DateGridResult users = userService.queryPageUserList(pageNum,pageSize);
		//添加数据模型
		mv.addObject("users", users.getRows());
		return mv;
	}
	
}
